package com.supermap.wzhy.common.aop;

import java.io.IOException;

import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;

public class MappingJackson2JsonpHttpMessageConverter
        extends MappingJackson2HttpMessageConverter {

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
        JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createJsonGenerator(outputMessage.getBody(), encoding);

        try {
            String jsonPadding = "";
            Object  o = object ;
            // If the callback doesn't provide, use the default callback
            if (object instanceof JSONPObject) {
                String jsonCallback = ((JSONPObject)object).getFunction();
                if (jsonCallback != null) {
                    jsonPadding = jsonCallback;
                    o = ((JSONPObject)object).getValue() ;
                }
            }
            if(jsonPadding.equals("")){
                super.writeInternal(o,outputMessage);
                return;
            }
            jsonGenerator.writeRaw(jsonPadding);
            jsonGenerator.writeRaw('(');
            this.getObjectMapper().writeValue(jsonGenerator, o);
            jsonGenerator.writeRaw(");");
            jsonGenerator.flush();
        } catch (JsonProcessingException ex) {
            super.writeInternal(object,outputMessage);
//            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }
}